package com.ruoyi.report_ys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.report_tg.domain.bo.TjssybgBsInfoBo;
import com.ruoyi.report_tg.domain.vo.TgsybgBaDetailVo;
import com.ruoyi.report_ys.domain.ReportYsDzkyqdsyBaDetail;
import com.ruoyi.report_ys.domain.ReportYsDzkyqdsybgBaDetail;
import com.ruoyi.report_ys.domain.vo.ReportYsDzkyqdsybgBaDetailVo;
import com.ruoyi.report_ys.mapper.ReportYsDzkyqdsybgBaDetailMapper;
import com.ruoyi.sycs.service.IBiQualificationService;
import com.ruoyi.syrw.annotation.FIllBasicInfo;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.report_ys.domain.bo.ReportYsDzkyqdsybgBsInfoBo;
import com.ruoyi.report_ys.domain.vo.ReportYsDzkyqdsybgBsInfoVo;
import com.ruoyi.report_ys.domain.ReportYsDzkyqdsybgBsInfo;
import com.ruoyi.report_ys.mapper.ReportYsDzkyqdsybgBsInfoMapper;
import com.ruoyi.report_ys.service.IReportYsDzkyqdsybgBsInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 岩石单轴抗压强度试验检测报告主Service业务层处理
 *
 * @author zyb
 * @date 2024-10-28
 */
@RequiredArgsConstructor
@Service
@Transactional
public class ReportYsDzkyqdsybgBsInfoServiceImpl implements IReportYsDzkyqdsybgBsInfoService {

    private final ReportYsDzkyqdsybgBsInfoMapper baseMapper;
    private final ReportYsDzkyqdsybgBaDetailMapper detailMapper;
    private final ISysDictDataService dictService;
    private final IBiQualificationService biQualificationService;

    /**
     * 查询岩石单轴抗压强度试验检测报告主
     */
    @Override
    @FIllBasicInfo
    public ReportYsDzkyqdsybgBsInfoVo queryById(Long excelId){
        ReportYsDzkyqdsybgBsInfoVo reportYsDzkyqdsybgBsInfoVo = baseMapper.selectVoById(excelId);
        List<ReportYsDzkyqdsybgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<ReportYsDzkyqdsybgBaDetail>()
            .eq(ReportYsDzkyqdsybgBaDetail::getExcelId, excelId));
        // 格式化 技术指标
        compute(baDetailVos);
        reportYsDzkyqdsybgBsInfoVo.setBaDetailVos(baDetailVos);
        // 生成报告结论
        // 如果已经有值了则不需要计算结论。
        if (StrUtil.isNotEmpty(reportYsDzkyqdsybgBsInfoVo.getJiancjl()) && !"检测结论：".equals(reportYsDzkyqdsybgBsInfoVo.getJiancjl()) && reportYsDzkyqdsybgBsInfoVo.getJiancjl().contains("检测结论")) {
            return reportYsDzkyqdsybgBsInfoVo;
        }
        return jcjl(reportYsDzkyqdsybgBsInfoVo);
    }


    /**
     * 查询岩石单轴抗压强度试验检测报告主列表
     */
    @Override
    public TableDataInfo<ReportYsDzkyqdsybgBsInfoVo> queryPageList(ReportYsDzkyqdsybgBsInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ReportYsDzkyqdsybgBsInfo> lqw = buildQueryWrapper(bo);
        Page<ReportYsDzkyqdsybgBsInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询岩石单轴抗压强度试验检测报告主列表
     */
    @Override
    public List<ReportYsDzkyqdsybgBsInfoVo> queryList(ReportYsDzkyqdsybgBsInfoBo bo) {
        LambdaQueryWrapper<ReportYsDzkyqdsybgBsInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ReportYsDzkyqdsybgBsInfo> buildQueryWrapper(ReportYsDzkyqdsybgBsInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ReportYsDzkyqdsybgBsInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTotalPage() != null, ReportYsDzkyqdsybgBsInfo::getTotalPage, bo.getTotalPage());
        lqw.eq(bo.getPage() != null, ReportYsDzkyqdsybgBsInfo::getPage, bo.getPage());
        lqw.eq(StringUtils.isNotBlank(bo.getBaogbh()), ReportYsDzkyqdsybgBsInfo::getBaogbh, bo.getBaogbh());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancdwmc()), ReportYsDzkyqdsybgBsInfo::getJiancdwmc, bo.getJiancdwmc());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcbwyt()), ReportYsDzkyqdsybgBsInfo::getGongcbwyt, bo.getGongcbwyt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpmc()), ReportYsDzkyqdsybgBsInfo::getYangpmc, bo.getYangpmc());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpbh()), ReportYsDzkyqdsybgBsInfo::getYangpbh, bo.getYangpbh());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsl()), ReportYsDzkyqdsybgBsInfo::getYangpsl, bo.getYangpsl());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpzt()), ReportYsDzkyqdsybgBsInfo::getYangpzt, bo.getYangpzt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsj()), ReportYsDzkyqdsybgBsInfo::getYangpsj, bo.getYangpsj());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancrq()), ReportYsDzkyqdsybgBsInfo::getJiancrq, bo.getJiancrq());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjwd()), ReportYsDzkyqdsybgBsInfo::getShiytjwd, bo.getShiytjwd());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjsd()), ReportYsDzkyqdsybgBsInfo::getShiytjsd, bo.getShiytjsd());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyj()), ReportYsDzkyqdsybgBsInfo::getJiancyj, bo.getJiancyj());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyj()), ReportYsDzkyqdsybgBsInfo::getPandyj, bo.getPandyj());
        lqw.eq(StringUtils.isNotBlank(bo.getZhuyyqsbmcjbh()), ReportYsDzkyqdsybgBsInfo::getZhuyyqsbmcjbh, bo.getZhuyyqsbmcjbh());
        lqw.eq(StringUtils.isNotBlank(bo.getQuydd()), ReportYsDzkyqdsybgBsInfo::getQuydd, bo.getQuydd());
        lqw.eq(StringUtils.isNotBlank(bo.getWeitrwbh()), ReportYsDzkyqdsybgBsInfo::getWeitrwbh, bo.getWeitrwbh());
        lqw.eq(StringUtils.isNotBlank(bo.getTuycd()), ReportYsDzkyqdsybgBsInfo::getTuycd, bo.getTuycd());
        lqw.eq(StringUtils.isNotBlank(bo.getDaibsl()), ReportYsDzkyqdsybgBsInfo::getDaibsl, bo.getDaibsl());
        lqw.eq(StringUtils.isNotBlank(bo.getFujsm()), ReportYsDzkyqdsybgBsInfo::getFujsm, bo.getFujsm());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancjl()), ReportYsDzkyqdsybgBsInfo::getJiancjl, bo.getJiancjl());
        lqw.eq(StringUtils.isNotBlank(bo.getShigwtdw()), ReportYsDzkyqdsybgBsInfo::getShigwtdw, bo.getShigwtdw());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcmc()), ReportYsDzkyqdsybgBsInfo::getGongcmc, bo.getGongcmc());
        lqw.eq(StringUtils.isNotBlank(bo.getShebIds()), ReportYsDzkyqdsybgBsInfo::getShebIds, bo.getShebIds());
        lqw.eq(StringUtils.isNotBlank(bo.getBgFlag()), ReportYsDzkyqdsybgBsInfo::getBgFlag, bo.getBgFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyjIds()), ReportYsDzkyqdsybgBsInfo::getJiancyjIds, bo.getJiancyjIds());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyjIds()), ReportYsDzkyqdsybgBsInfo::getPandyjIds, bo.getPandyjIds());
        lqw.eq(bo.getExcelResult() != null, ReportYsDzkyqdsybgBsInfo::getExcelResult, bo.getExcelResult());
        lqw.eq(StringUtils.isNotBlank(bo.getShiyyt()), ReportYsDzkyqdsybgBsInfo::getShiyyt, bo.getShiyyt());
        lqw.eq(StringUtils.isNotBlank(bo.getYansclms()), ReportYsDzkyqdsybgBsInfo::getYansclms, bo.getYansclms());
        lqw.eq(StringUtils.isNotBlank(bo.getShijxz()), ReportYsDzkyqdsybgBsInfo::getShijxz, bo.getShijxz());
        return lqw;
    }

    /**
     * 新增岩石单轴抗压强度试验检测报告主
     */
    @Override
    @DSTransactional
    public Boolean insertByBo(ReportYsDzkyqdsybgBsInfoBo bo) {
        ReportYsDzkyqdsybgBsInfo add = BeanUtil.toBean(bo, ReportYsDzkyqdsybgBsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExcelId(add.getExcelId());
            // 新增详情 12 行
            ArrayList<ReportYsDzkyqdsybgBaDetail> details = new ArrayList<>(12);
            for (long i = 1; i <= 12L; i++) {
                details.add(new ReportYsDzkyqdsybgBaDetail(add.getExcelId(), i));
            }
            detailMapper.insertBatch(details);
        }
        return flag;
    }

    /**
     * 修改岩石单轴抗压强度试验检测报告主
     */
    @Override
    public Boolean updateByBo(ReportYsDzkyqdsybgBsInfoBo bo) {
        //是否合格判断填充
        fillExcelResult(bo);
        ReportYsDzkyqdsybgBsInfo update = BeanUtil.toBean(bo, ReportYsDzkyqdsybgBsInfo.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag){
            detailMapper.updateBatchById(BeanUtil.copyToList(bo.getBaDetailVos(), ReportYsDzkyqdsybgBaDetail.class));
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ReportYsDzkyqdsybgBsInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    private void fillExcelResult(ReportYsDzkyqdsybgBsInfoBo bo) {
        if (CollUtil.isNotEmpty(bo.getBaDetailVos())) {
            bo.setExcelResult(2);
        }
        bo.setExcelResult(0);
    }

    @Override
    public boolean isWell(Long excelId) {
        return baseMapper.selectVoById(excelId).getExcelResult() != 2;
    }

    /**
     * 批量删除岩石单轴抗压强度试验检测报告主
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    public List<ReportYsDzkyqdsybgBaDetailVo> compute(List<ReportYsDzkyqdsybgBaDetailVo> voList) {
        voList.forEach(v -> {
            if (ObjUtil.isNull(v.getQualId())) {
                throw new ServiceException("qualId不能为空");
            }
            // 1. 根据不同符号 格式化技术指标 && 结果判定
            if (StrUtil.isEmpty(v.getSymbolValue())) {
                v.setJiszb("-");
                if (ObjUtil.isNotNull(v.getJiancjg())) {
                    v.setJiegpd("实测值");
                } else {
                    v.setJiegpd("-");
                }
                return;
            }
            if (StringUtils.isNotEmpty(v.getSymbolValue())){
                switch (v.getSymbolValue()) {
                    case "01":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "01") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) < 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "02":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "02") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) > 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "03":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "03") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) == 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "04":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "04") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().abs().compareTo(v.getNum1().abs()) <= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "05":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "05") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().abs().compareTo(v.getNum1().abs()) >= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "06":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "06") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().abs().compareTo(v.getNum1().abs()) <= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "07":
                        if (ObjUtil.isNotNull(v.getNum1()) && ObjUtil.isNotNull(v.getNum2())) {
                            v.setJiszb("≥" + BigDecimalUtil.stpTrailZero(v.getNum1()) + ",≤" + BigDecimalUtil.stpTrailZero(v.getNum2()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) >= 0 && v.getJiancjg().compareTo(v.getNum2()) <= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "08":
                        if (ObjUtil.isNotNull(v.getNum1()) && ObjUtil.isNotNull(v.getNum2())) {
                            v.setJiszb(">" + BigDecimalUtil.stpTrailZero(v.getNum1()) + ",≤" + BigDecimalUtil.stpTrailZero(v.getNum2()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) > 0 && v.getJiancjg().compareTo(v.getNum2()) <= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "09":
                        if (ObjUtil.isNotNull(v.getNum1()) && ObjUtil.isNotNull(v.getNum2())) {
                            v.setJiszb("≥" + BigDecimalUtil.stpTrailZero(v.getNum1()) + ",<" + BigDecimalUtil.stpTrailZero(v.getNum2()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) >= 0 && v.getJiancjg().compareTo(v.getNum2()) < 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "10":
                        if (ObjUtil.isNotNull(v.getNum1()) && ObjUtil.isNotNull(v.getNum2())) {
                            v.setJiszb(">" + BigDecimalUtil.stpTrailZero(v.getNum1()) + ",<" + BigDecimalUtil.stpTrailZero(v.getNum2()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) > 0 && v.getJiancjg().compareTo(v.getNum2()) < 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                }
            }
        });
        return voList;
    }

    private ReportYsDzkyqdsybgBsInfoVo jcjl(ReportYsDzkyqdsybgBsInfoVo reportYsDzkyqdsybgBsInfoVo) {
        List<ReportYsDzkyqdsybgBaDetailVo> baDetailVos = reportYsDzkyqdsybgBsInfoVo.getBaDetailVos();
        if (CollectionUtil.isNotEmpty(baDetailVos)){
            boolean flag = baDetailVos.stream().anyMatch(dv -> "不符合".equals(dv.getJiegpd()));
            if (flag){
                return reportYsDzkyqdsybgBsInfoVo;
            }
        }
        String result = "检测结论：依据《公路工程岩石实验规程》" +
            reportYsDzkyqdsybgBsInfoVo.getJiancyj() + "，检测指标符合设计文件的要求，可以用于路基工程。";
        reportYsDzkyqdsybgBsInfoVo.setJiancjl(result);
        return reportYsDzkyqdsybgBsInfoVo;
    }
}
